<template>
    <el-form-item label="数据源" prop="readerDatasourceId">
        <el-select v-model="form.readerDatasourceId" filterable @change="rDsChange">
            <el-option
                    v-for="item in  sourceList.filter(e=>e.datasourceType.indexOf('ftp')==-1)" :key="item.datasourceId"
                    :label="item.datasourceName + '_' + item.datasourceType"
                    :value="item.datasourceId"/>
        </el-select>
    </el-form-item>
  <!--    <el-form-item v-show="datasourceType==='postgresql' || datasourceType==='oracle'" label="Schema："-->
  <!--                  prop="tableSchema">-->
  <!--        <el-select v-model="form.tableSchema" filterable @change="schemaChange">-->
  <!--            <el-option v-for="item in schemaList" :key="item" :label="item" :value="item"/>-->
  <!--        </el-select>-->
  <!--    </el-form-item>-->
    <el-form-item label="数据库表名：" prop="readerTables">
        <el-select v-model="form.readerTables" default-first-option filterable
                   @change="rTbChange">
            <el-option v-for="item in rTbList" :key="item" :label="item" :value="item"/>
        </el-select>
    </el-form-item>
    <el-form-item label="SQL语句" prop="querySql">
        <el-input type="textarea" v-model="form.querySql" placeholder="请输入SQL语句，可配合同步方式，如：select * from A where  create_time > ${time_start} and create_time <= ${time_end}" clearable />
        <el-button type="primary" @click="rSqlChange" style="float: right;">解析字段</el-button>
    </el-form-item>
    <el-form-item label="切分字段" prop="splitPk">
        <el-input v-model="form.splitPk" placeholder="请输入切分字段" clearable/>
    </el-form-item>
    <el-form-item label="同步方式" prop="syncMode">
        <el-select v-model="form.syncMode" default-first-option filterable placeholder="请选择同步方式">
            <el-option v-for="item in dayWayList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"/>
        </el-select>
<!--        <el-input v-model="form.syncField" placeholder="请输入同步字段" clearable/>-->
    </el-form-item>
    <el-form-item v-show="form.syncMode !== '6'" label="字段变量" prop="syncField">
        <el-input v-model="form.syncField" placeholder="请输入需要传入的字段变量，配合sql语句中的条件表达式，如：time" clearable/>
    </el-form-item>

    <el-form-item v-show="form.syncMode !== '6'" label="字段类型" prop="syncFieldType">
        <el-select v-model="form.syncFieldType" placeholder="请选择字段类型" default-first-option filterable>
            <el-option v-for="item in syncFieldTypeList" :key="item" :label="item" :value="item"/>
        </el-select>
    </el-form-item>
    <el-form-item v-show="form.syncMode !== '6'" label="字段格式" prop="syncFieldDateformat">
        <el-select v-model="form.syncFieldDateformat" placeholder="请选择字段类型" default-first-option filterable>
            <el-option v-for="item in syncFieldDateformatList" :key="item" :label="item" :value="item"/>
        </el-select>
    </el-form-item>
    <el-form-item v-show="form.syncMode === '7'" label="最新同步记录值" prop="lastSuccValue">
      <el-input v-model="form.lastSuccValue" placeholder="请输入最新的同步记录值" clearable/>
    </el-form-item>
</template>


<script setup>
import {onMounted, reactive, ref, watch} from "vue";
import { selectTables, selectSchema, selectColumns, selectTableInfo, selectColumnsByQuerySql } from '@data/api/data/datacollection'
import {ElMessage} from "element-plus";
import { cloneDeep } from 'lodash-es'

const props = defineProps({
    form: {
        type: Object,
        default: () => {
        }
    },
    sourceList: {
        type: Array,
        default: () => []
    },
    dayWayList: {
        type: Array,
        default: () => []
    },
});
const form = reactive(props.form);

const datasourceType = ref('');
const schemaList = ref([]);
const rTbList = ref([]);
const syncFieldTypeList = ref(['Date','TimeStamp','String'])
const syncFieldDateformatList = ref(['yyyy-MM-dd','yyyyMMdd','yyyy-MM-dd HH:mm:ss', 'yyyy-MM-dd HH:mm'])




const getSchema = () => {
    if (form.readerDatasourceId) {
        const obj = {
            datasourceId: form.readerDatasourceId
        }
        selectSchema(obj).then(response => {
            schemaList.value = response.data
        })
    }
}

const getTables = (type) => {
    if (type === 'rdbmsReader') {
        console.log("=======:" + form.readerDatasourceId)
        if (form.readerDatasourceId) {
            let obj = {}
            if (datasourceType.value === 'postgresql' || datasourceType.value === 'oracle') {
                obj = {
                    datasourceId: form.readerDatasourceId,
                    // tableSchema: form.tableSchema
                }
            } else {
                obj = {
                    datasourceId: form.readerDatasourceId
                }
            }
            // 组装
            selectTables(obj).then(response => {
                if (response) {
                    rTbList.value = response.data
                }
            })
        }
    }
}


// schema 切换
// const schemaChange = (e) => {
//     form.tableSchema = e
//     // 获取可用表
//     getTables('rdbmsReader')
// }


const rDsChange = (e) => {
    // 清空
    form.readerTables = ''
    form.querySql = ''
    datasourceType.value = props.sourceList.find((item) => item.datasourceId === e).datasourceType;
    getTables('rdbmsReader')

}

// 表切换
const rTbChange = (e) => {
    form.querySql = ''
    form.readerTables = e
    form.fColumnList = []
    form.querySql = `select * from ${e}`;
    getTableColumns();
}
// 表字段切换
const rSqlChange = () =>{
      const regex = /select\s+(\w+|\*)\s+from\s+(\w+)/;
      let query = form.querySql.match(regex);
      getColumnsByQuerySql();
      // if(query[1] === '*') {
      //     getTableColumns();
      // } else {
      //     getColumnsByQuerySql();
      // }
}
const getTableColumns = async () => {
    //获取表所有字段名
    await selectColumns({
        'datasourceId': form.readerDatasourceId,
        'tableName': form.readerTables
    }).then(response => {
        let arr = []
        response.data.forEach(item => {
            arr.push({
                name:item,
                isChecked:false
            })
        })

        form.fColumnListRaw = cloneDeep(arr);
        form.fColumnList = arr
        ElMessage.success('解析成功')
    })

    console.log(props.form)

}
const getColumnsByQuerySql = () => {
    const obj = {
        datasourceId: form.readerDatasourceId,
        querySql:  form.querySql
    }
    // this.loading = true
    selectColumnsByQuerySql(obj).then(response => {
        let arr = []
        response.data.forEach(item => {
            arr.push({
                name:item,
                isChecked:false
            })
        })

        form.fColumnListRaw = cloneDeep(arr);
        form.fColumnList = arr
        ElMessage.success('解析成功')
    })

}

onMounted(() => {
  getTables('rdbmsReader');
})
</script>

<style scoped>

</style>